<?php

namespace App\Http\Controllers;

use EasyWeChat\Kernel\Messages\Message;

use App\Wechat\Messages\TextMessage;
use App\Wechat\Messages\ImageMessage;
use App\Wechat\Messages\VideoMessage;
use App\Wechat\Messages\VoiceMessage;
use App\Wechat\Messages\LocationMessage;
use App\Wechat\Messages\EventMessage;
use Illuminate\Http\Request;
use App\Models\WxUser;
use Storage;
use App\Models\PriDeviceInfo;
// use JWTAuth;

class WeChatController extends Controller
{
    public function __construct() {
       // $this->middleware('auth:api', ['except' => ['serve', 'jssdk', 'genCode', 'jssdk', 'wecallback']]);
       // $this->middleware('api')->only('serve');
    }
    /**
     * 处理微信的请求消息
     *
     * @return string
     */
    public function serve()
    {

        $app = app('wechat.official_account');
        
        $app->server->push(function($message){
            $this->unsubscribe($message);
            $this->subscribe($message);
            return "澳天智能欢迎您！";
        });
        

//        $messageMap = [
//            [ TextMessage::class, Message::TEXT],
//            [ ImageMessage::class, Message::IMAGE],
//            [ VideoMessage::class, Message::VIDEO],
//            [ VoiceMessage::class, Message::VOICE],
//            [ LocationMessage::class, Message::LOCATION],
//            [ EventMessage::class, Message::EVENT],
//        ];
//        foreach ($messageMap as $v) {
//            list($handler, $type) = $v;
//            $app->server->push($handler, $type);
//        }

        return $app->server->serve();
    }
    
    //取消订阅
    protected function unsubscribe($message) {
        if($message['MsgType']=='event' && $message['Event']=='unsubscribe'){
            $openId = $message['FromUserName'];
            WxUser::where('openid', $openId)->update(['user_id' => null, 'status'=>0]);
        }
    }
    
    //订阅
    protected function subscribe($message) {
        if($message['MsgType']=='event' && $message['Event']=='subscribe'){
            $openId = $message['FromUserName'];
            WxUser::where('openid', $openId)->update(['status'=>1]);
        }
    }
    
    
    //检查是否绑定用户
    protected function checkUser($openid) {
        $info = WxUser::where('openid', $openid)->first();
        return $info;
    }
    
    //生成设备二维码
    public function genCode(Request $request) {
        $deviceId = $request->input('device_id', '');
        $info = PriDeviceInfo::find($deviceId);
        if($info->code_url){
            return [ 'code_url' => $info->code_url, 'code_png' => $info->code_png ];
        }
        $app = app('wechat.official_account');
        $result = $app->qrcode->forever($deviceId);
        $ticket = data_get($result, 'ticket');
        $url = $app->qrcode->url($ticket);
        $content = file_get_contents($url); // 得到二进制图片内容
        $path='official_account/'.$deviceId.'.png';
        Storage::disk('upload')->put($path, $content);
        return [ 'code_url' => $url, 'code_png' => $path ];
    }
    
    //jssdk参数
    public  function jssdk(Request $request){
        $app = app('wechat.official_account');
        $url = $request->input('url');
        $app->jssdk->setUrl($url);
        return $app->jssdk->buildConfig(['scanQRCode'], false);
    }
    
    public function wecallback(Request $request)
    {
        $app = app('wechat.official_account');
        $sessionKey = \sprintf('wechat.oauth_user.default');

        $user = session($sessionKey, []);
        
        $isBind = false;
        
      // return ['user'=>['id'=>1], 'hasUser'=>$isBind];
        if (!$user) {
            if ($request->has('code')) {
                $user = $app->oauth->user();
                $openId = $user->getId();
                $info = $this->checkUser($openId);
                if(!$info){
                    WxUser::create($user->getOriginal());
                }
                if($info&&$info->user_id){
                    $isBind = true;
                }
                session([$sessionKey => $user]);
            }
        }
        return ['user'=>$user, 'hasUser'=>$isBind];
    }
}
